import axios from 'axios'
import useToken from '../store/token'
import { ElLoading } from 'element-plus'
import config from '../config'
import notification from './notification'
import router from '../router/router'
import { login } from '../api/api'

const baseURL = config.baseURL

var loadingInstance = null

const service = axios.create({ baseURL })

service.interceptors.request.use(config => {
    loadingInstance = ElLoading.service()
    const { token } = useToken()
    if (token) {
        config.headers.jwt = token

    }
    return config
})

service.interceptors.response.use(
    response => {
        loadingInstance.close()
        const { statusCode, data, message } = response.data
        console.log('ok:' + response);
        if (statusCode === 200) {
            notification({
                message: message,
                type: 'success'
            })
            return data || true
        }

        notification({
            message: message,
            type: 'error'
        })
        if (statusCode === 1000 || statusCode === 401) {
            router.push({ name: 'login' })
        }

        return false
    },
    error => {
        loadingInstance.close()
            //const { statusCode, data, message } = error.response.data

        notification({
            message: '请求失败',
            type: 'error'
        })


        console.log(error)
    }
)

export default service